package com.example.srm.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.srm.auth.anno.Authority;
import com.example.srm.auth.mapper.TUserMapper;
import com.example.srm.auth.service.TUserService;
import com.example.srm.constant.PermissionConstant;
import com.example.srm.constant.RoleConstant;
import com.example.srm.domain.TRole;
import com.example.srm.domain.tree.Tree;
import com.example.srm.domain.vo.PageView;
import com.example.srm.domain.vo.Result;
import com.example.srm.auth.service.TPermissionService;
import com.example.srm.auth.service.TRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author pfk
 * @creatTime 2021/11/24 21:21
 * @describe    角色类操作
 */
@RestController
@RequestMapping("/role")
@CrossOrigin
public class RoleController {
    
    @Autowired
    private TRoleService roleService;
    @Autowired
    private TPermissionService permissionService;
    @Autowired
    private TUserService userService;



    /**
     * 查询角色
     */
    @RequestMapping(value = "/query",method = RequestMethod.GET)
    @Authority(auth = "account:role:list")
    public Result query(Integer page,Integer pageSize){
        //校验参数是否合法
        if (page==null||page<0){
            page=1;
        }
        if (pageSize==null||pageSize<=0){
            pageSize=10;
        }
        Page<TRole> rolePage = roleService.page(new Page<>(page,pageSize));
        PageView<TRole> pageView = new PageView<TRole>()
                .setRows(rolePage.getRecords())
                .setTotalCount(rolePage.getTotal())
                .setTotalPage(new Integer(rolePage.getPages()+""));

        return new Result().setData(pageView).setSuccess(true);
    }

    /**
     * 保存角色
     * @param roleView
     * @return
     * @throws Exception
     */
    @PostMapping("")
    @Authority(auth = "account:role:add")
    public Result save(@RequestBody TRole roleView) throws Exception {
        TRole role = roleService.getOne(new QueryWrapper<TRole>().eq(RoleConstant.name, roleView.getName()));
        if (role!=null) {
            return new Result().setMsg("角色"+roleView.getName()+"已经存在");
        }
        boolean save = roleService.save(roleView);
        return new Result().setSuccess(save);
    }

    /**
     * 修改角色
     * @param roleView
     * @return
     * @throws Exception
     */
    @PutMapping("")
    @Authority(auth = "account:role:update")
    public Result update(@RequestBody  TRole roleView ) throws Exception {
        //判断修改的角色是否存在
        TRole idRole = roleService.getOne(new QueryWrapper<TRole>().eq(RoleConstant.id, roleView.getId()));
        if (idRole==null) {
            return new Result().setMsg("角色"+roleView.getName()+"不存在");
        }
        TRole nameRole = roleService.getOne(new QueryWrapper<TRole>().eq(RoleConstant.name, roleView.getName()));
        if (nameRole!=null) {
            return new Result().setMsg("角色名为"+roleView.getName()+"已经存在");
        }
        boolean updateById = roleService.updateById(roleView);
        return new Result().setSuccess(updateById);
    }

    /**
     * 根据id查询角色
     * @param id
     * @return
     */
    @GetMapping(value = "",params = {"id"})
    public Result findById(String id){
        TRole role = roleService.getById(id);
        return new Result().setData(role).setSuccess(true);
    }

    /**
     * 删除角色
     * @param id
     * @return
     */
    @DeleteMapping(value = "",params = {"id"})
    @Authority(auth = "account:role:delete")
    public Result delete(String id){
        TRole role = roleService.getById(id);
        if (role==null) {
            return new Result().setMsg("删除失败，用户不存在");
        }
        boolean remove = roleService.removeById(id);
        return new Result().setSuccess(remove);
    }

    /**
     * 告诉前端跳转分配权限页面
     * @param id
     * @return
     */
    @GetMapping(value = "/to_assignment",params = {"id"})
    public Result toAssignmentPermission(String id){
        // 查询所有的权限树　
        List<Tree> permissionTree = permissionService.findPermissionTree();
        // 查询角色已经有的权限ids
        Set<String> rolePermissionIds = roleService.findPermissionIdsById(id);
        //将数据装进map中返回
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("permissionTree",permissionTree);
        dataMap.put("rolePermissionIds",rolePermissionIds);

        return new Result().setSuccess(true).setData(dataMap);
    }

    /**
     * 分配权限
     * @param id
     * @param permissionIds
     * @return
     * @throws Exception
     */
    @PutMapping(value = "/assignment",params = {"id"})
    @Authority(auth = "account:role:permission")
    public Result assignmentPermission(String id, @RequestBody String[] permissionIds)throws Exception{
        boolean assignment = roleService.assignmentPermission(id,permissionIds);
        //更新redis里的权限
        boolean update2  =userService.updatePermissionForRedis(id);
        return new Result().setSuccess(assignment);
    }

}
